<template>
    <div class="examination">
        <el-card class="examination_card">
            <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb_post">
                <el-breadcrumb-item :to="{path: '/info'}">首页</el-breadcrumb-item>
                <el-breadcrumb-item>审批</el-breadcrumb-item>
                <el-breadcrumb-item>申请审批</el-breadcrumb-item>
            </el-breadcrumb>
            <el-table ref="examine_leave_list" :data="wait2Examine" 
            class="wait_examine" style="width: 95%; margin: auto;" stripe>
                <el-table-column
                type="selection"
                align="center"
                width="55">
                </el-table-column>
                <el-table-column
                label="申请序号"
                prop="appID"
                align="center"
                width="70">
                </el-table-column>
                <el-table-column
                prop="startTime"
                label="开始时间"
                width="100">
                </el-table-column>
                <el-table-column
                prop="endTime"
                label="结束时间"
                width="100">
                </el-table-column>
                <el-table-column
                width="55"
                label="类型">
                    <template slot-scope="scope">
                        <p>
                            {{leave_type[scope.row.type]}}
                        </p>
                    </template>
                </el-table-column>
                <el-table-column
                prop="reason"
                label="申请理由">
                </el-table-column>
                <el-table-column
                label="申请人"
                prop="empName"
                width="95">
                </el-table-column>
                <el-table-column
                label="申请人编号"
                prop="empID"
                width="95">
                </el-table-column>
                <el-table-column
                label="申请状态"
                width="160">
                <template slot-scope="scope">
                    <p>
                        {{leave_state[scope.row.state]}}
                    </p>
                </template>
                </el-table-column>
            </el-table>
            <el-row style="margin-top: 1%; margin-bottom: 1%; margin-left: 2.5%;">
                <el-button type="success" class="approve_btn" @click="clickBatchBtn('approval')">批准</el-button>
                <el-button type="danger" class="refuse_btn" @click="clickBatchBtn('refusal')">拒绝</el-button>
            </el-row>
        </el-card>
        <el-dialog title="审批意见" :visible.sync="commentvisible">
            <el-row>
                <el-input type="textarea" v-model="comment" placeholder="请输入审批意见" style="width:80%">
                </el-input>
            </el-row>
            <el-row style="margin-top:1%">
                <el-button type="primary" @click="handleSelection()">提交</el-button>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            wait2Examine: [],
            approval_list: [],
            commentvisible: false, 
            comment: '',
            decision: '',
            leave_type: ['出差', '婚假', '产假', '年假', '事假', '病假'],
            leave_state: ['被拒绝', '待部门经理审批', '待副总经理审批', '待总经理审批', '已批准'],

        }
    },
    methods: {
        findIndex(arr, obj) {
            let obj_str = JSON.stringify(obj);
            return arr.reduce((index, element, i) => {
                if (JSON.stringify(element) == obj_str) {
                    return i;
                }
                else {
                    return index;
                }
            })
        },
        date2Str(date) {
            let month = (date.getMonth() + 1 > 9? date.getMonth() + 1 : "0" + (date.getMonth() + 1));
            let day = (date.getDate() > 9? date.getDate() : "0" + date.getDate());
            return date.getFullYear() + '-' + month + '-' + day;
        },
        clickBatchBtn(val) {
            this.decision = val;
            this.commentvisible = true;
            this.approval_list = this.$refs.examine_leave_list.selection;
        },
        handleSelection() {
            let that = this;
            console.log(this.$refs.examine_leave_list.selection)
            for(let i = 0; i < that.approval_list.length; i++) {
                fetch('http://localhost:9095/AttendanceSystem/leave', {
                    method: 'PUT',
                    body: JSON.stringify({
                        Leave: {
                            "appID": that.approval_list[i].appID,
                            "empID": that.approval_list[i].empID,
                            "state": (that.decision == 'approval'? (parseInt(that.approval_list[i].state) + 1).toString() : '0')
                        }
                    }),
                    headers: new Headers({
                        'Content-Type': 'application/json',
                        'username': that.$store.state.username,
                        'Token': that.$store.state.token
                    })
                }).then(res => {
                    if (res.status == 200) {
                        console.log('decision', that.decision);
                        that.$message({
                            showClose: true,
                            message: '申请编号 ' + that.approval_list[i].appID + ' 审批意见添加成功',
                            type: 'success'
                        });
                        fetch('http://localhost:9095/AttendanceSystem/approval', {
                            method: 'POST',
                            headers: new Headers({
                                'Content-Type': 'application/json;charset=UTF-8',
                                'username': that.$store.state.username,
                                'Token': that.$store.state.token
                            }),
                            body: JSON.stringify({
                                Approval: {
                                    empID: that.$store.state.username,
                                    time: that.date2Str(new Date()),
                                    appID: that.approval_list[i].appID,
                                    type: (that.decision == 'approval'? (parseInt(that.$store.state.auth)).toString() : '0'),
                                    approval: (that.decision == 'approval'? true : false),
                                    comment: that.comment
                                }
                            })
                        });
                        
                    }
                })
                let index = that.findIndex(that.wait2Examine, that.approval_list[i]);
                that.wait2Examine.splice(index, 1);
            }
            that.$message({
                showClose: true,
                message: '批量审批意见提交成功',
                type: 'success'
            });
            that.commentvisible = false;
        }
    },
    beforeRouteEnter(to, from, next) {
        console.log('from', from.path, 'to', to.path);
        next(vm => {
            if(vm.$store.state.auth >= 1) {
                fetch('http://localhost:9095/AttendanceSystem/leave', {
                    method: 'GET',
                    headers: new Headers({
                        'Content-Type': 'application/json',
                        'username': (vm.$store.state.username == null? sessionStorage.getItem("username") : vm.$store.state.username),
                        'Token': (vm.$store.state.token == null? sessionStorage.getItem("token") : vm.$store.state.token)
                    })
                }).then(res => res.json())
                .then(json => {
                    let i = 0;
                    vm.wait2Examine = [];
                    for(i = 0; i < json.length; i++) {
                        if (json[i].state == (vm.$store.state.auth)) {
                            if (json[i].empDeptID == vm.$store.state.department_id && vm.$store.state.auth == 1) {
                                vm.wait2Examine.push(json[i]);
                            }
                            else if (vm.$store.state.auth > 1) {
                                vm.wait2Examine.push(json[i]);
                            }
                        }
                    }
                })
            }
            else {
                vm.$router.push('/info');
                vm.$message({
                    showClose: true,
                    type: 'error',
                    message: '权限不足'
                });
            }
        })
    }
}
</script>

<style>
.examination_card{
    margin-top: 1%;
    margin-left: 3%;
    margin-right: 3%;
}
.breadcrumb_post {
    margin-bottom: 2%;
}
</style>